package qmlt.dataset.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EntropyUtils
{
    public static double log2(double x)
    {
        return Math.log(x) / Math.log(2);
    }

    public static float calculateEntropy(List<Object> setOfClass)
    {
        Map<Object, Integer> map = new HashMap<Object, Integer>();

        for (Object c : setOfClass)
        {
            if (!map.containsKey(c))
            {
                map.put(c, 1);
            }
            else
            {
                int pre = map.get(c);
                map.put(c, pre + 1);
            }
        }

        float entropy = 0;
        for (Object c : map.keySet())
        {
            float ratio = (float) map.get(c) / setOfClass.size();
            entropy -= ratio * log2(ratio);
        }

        return entropy;
    }

    public static float calculateInfoGain(int size, float entropy, List<Object>... subsetsOfClass)
    {
        float gain = entropy;
        for (List<Object> subset : subsetsOfClass)
        {
            float ratio = (float) subset.size() / size;
            gain -= ratio * calculateEntropy(subset);
        }
        return gain;
    }
}
